import { useState, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import {
  ContactFormData,
  submitContactForm,
  validateContactForm,
  ContactSubmitResponse
} from '@/lib/api/contact'

export interface UseContactReturn {
  isSubmitting: boolean
  submitForm: (formData: ContactFormData) => Promise<boolean>
  validateForm: (formData: ContactFormData) => {
    isValid: boolean
    errors: Partial<Record<keyof ContactFormData, string>>
  }
}

export const useContact = (): UseContactReturn => {
  const { t } = useTranslation()
  const [isSubmitting, setIsSubmitting] = useState(false)

  // 表单验证
  const validateForm = useCallback((formData: ContactFormData) => {
    return validateContactForm(formData)
  }, [])

  // 提交表单
  const submitForm = useCallback(async (formData: ContactFormData): Promise<boolean> => {
    try {
      setIsSubmitting(true)

      // 客户端验证
      const validation = validateContactForm(formData)
      if (!validation.isValid) {
        const firstError = Object.values(validation.errors)[0]
        toast.error(firstError)
        return false
      }

      // 提交表单
      const response: ContactSubmitResponse = await submitContactForm(formData)

      // 显示成功消息
      toast.success(response.message || t('aboutPages.contact.submitSuccess'))

      return true

    } catch (error) {
      console.error('提交联系表单失败:', error)

      // 显示错误消息
      toast.error(
        error instanceof Error
          ? error.message
          : t('aboutPages.contact.submitError') || '提交失败，请稍后重试'
      )

      return false
    } finally {
      setIsSubmitting(false)
    }
  }, [t])

  return {
    isSubmitting,
    submitForm,
    validateForm
  }
}
